<?php

declare(strict_types=1);

namespace Service\ConfigService;

use App\Model\BbcModel\Config;
use App\Model\BbcModel\ConfigChannel;
use App\Model\BbcModel\Layout;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\MnChannel;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\OpenStoreConfig;
use App\Model\BbcModel\SmsCode;
use Service\BaseService;
use Service\Code\Normal;
use Service\HelperService\Common;
use Service\LayoutService\LayoutService;

class MnConfigService extends BaseService
{
    /**
     * 判断是否开通渠道
     * @param int $mnid
     * @param int $mid
     * @return array
     */
    public function checkStore(int $mnid, int $mid)
    {
        if (empty($mid)) {
            return Normal::returnCode(Normal::FAIL, '未登录');
        }
        $user = MnChannel::instance()->info(['mid' => $mid]);
        if (empty($user)) {
            return Normal::returnCode(Normal::FAIL, '您还未申请成为渠道商');
        }
        if ($user['status'] == 0) {
            return Normal::returnCode(Normal::FAIL, '渠道已被禁用');
        }
        if ($user['check_status'] == 1) {
            return Normal::returnCode(Normal::SUC, '您已经审核通过', $user['id']);
        }
        if ($user['check_status'] == 0) {
            return Normal::returnCode(Normal::FAIL, '您的资料正在审核中');
        }
        if ($user['check_status'] == 2) {
            return Normal::returnCode(Normal::FAIL, '您提交的审核未通过');
        }
        return Normal::returnCode(Normal::FAIL, '参数有误');
    }

    /**
     * 判断是否开通Q店 function
     * @param int $mnid
     * @param int $cid
     * @param int $mid
     * @return array
     */
    public function checkGlobalStore(int $mnid, int $cid, int $mid)
    {
        if (empty($mid)) {
            return Normal::returnCode(Normal::FAIL, '未登录');
        }

        $userObj = Mnuser::instance()->where([
            'mnid' => $mnid,
            'mid' => $mid,
            'status' => 1,
            'new_store' => 1,
            'pid' => $cid,
        ])->orderBy('id', 'desc')->first();

        if (empty($userObj)) {
            return Normal::returnCode(Normal::FAIL, '未开通小店');
        }

        $user = $userObj->toArray();

        if ($user['is_pay'] == 0) {
            return Normal::returnCode(Normal::FAIL, '未付款');
        }
        if ($user['check_status'] == 0) {
            return Normal::returnCode(Normal::FAIL, '小店正在审核中');
        }
        if ($user['check_status'] == 2) {
            return Normal::returnCode(Normal::FAIL, '未开通小店');
        }

        return Normal::returnCode(Normal::SUC, '已开通小店', $user['id']);
    }

    /**
     * 获取邀请开店页面富文本内容
     * @param int $mnid
     * @param int $cid
     * @return array
     */
    public function getText(int $mnid, int $cid)
    {
        if ($mnid == 2) {
            $Qstroe = Config::instance()->info(['code' => 'wx_mnapp']);
        } else {
            $Qstroe = Config::instance()->info(['code' => 'wx_q_mnapp']);
        }
        $Qstroe = json_decode($Qstroe['value'], true);
        $disContent = str_replace("http://shop.indoorbuy.com/", Common::$pre_image_url, $Qstroe['dis_content']);
        return Normal::returnCode(Normal::SUC, '请求成功', $disContent);
    }

    /**
     * 获取开店图片
     * @param int $mnid
     * @param int $cid
     * @return array
     */
    public function getImage(int $mnid, int $cid)
    {
        if ($mnid == 2) {
            $image = ConfigChannel::instance()->info(['code' => 'wx_mnapp', 'cid' => $cid, 'status' => 1]);
        } else {
            $image = ConfigChannel::instance()->info(['code' => 'wx_q_mnapp', 'cid' => $cid, 'status' => 1]);
        }
        if (empty($image)) {
            return Normal::returnCode(Normal::SUC, '请求成功', 'https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/new/upload/20211229/164076210090407.png');
        }
        $image = json_decode($image['value'], true)['img'];
        if (empty($image)) {
            return Normal::returnCode(Normal::SUC, '请求成功', 'https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/new/upload/20211229/164076210090407.png');
        }
        return Normal::returnCode(Normal::SUC, '请求成功', $image);
    }

    /**
     * 开通小店
     * @param array $params
     * @return array
     */
    public function openStore(array $params)
    {
        if (empty($params['mid'])) {
            return Normal::returnCode(Normal::FAIL, '未登录');
        }
        $params['channel_id'] = $params['cid'] ?? $params['channel_id'];
        if (empty($params['channel_id'])) {
            return Normal::returnCode(Normal::FAIL, '请传入所属渠道');
        }
        $params['is_pay'] = $params['is_pay'] ?? 0;
        $channel = MnChannel::instance()->info(['id' => $params['channel_id'], 'status' => 1, 'check_status' => 1]);
        if (empty($channel)) {
            return Normal::returnCode(Normal::FAIL, '渠道不存在');
        }
        $isExistStore = Mnuser::instance()->info([
            'mnid' => $params['mnid'],
            'mid' => $params['mid'],
            'new_store' => 1,
            'is_pay' => 1,
            'pid' => $params['channel_id'],
            '_order_' => 'id desc'
        ]);
        if (!empty($isExistStore)) {
            if ($isExistStore['check_status'] == 0) {
                return Normal::returnCode(Normal::FAIL, '店铺正在审核中');
            }
            if ($isExistStore['status'] == 1 && $isExistStore['check_status'] == 1) {
                return Normal::returnCode(Normal::FAIL, '您已经开通店铺');
            }
            if ($isExistStore['status'] == 0) {
                return Normal::returnCode(Normal::FAIL, '您已经开通店铺，但是店铺被禁用了');
            }
        }
        $config = OpenStoreConfig::instance()->info(['cid' => $params['channel_id']]);
        //0-自动审核，1-人工审核
        if (empty($config)) {
            $checkNeeds = 1;
        } elseif ($config['audit_type'] == 0) {
            $checkNeeds = 0;
        } else {
            $checkNeeds = 1;
        }

        $insertMuUser = [
            'sale_id' => $params['sale_id'] ?? '',
            'mnid' => $params['mnid'],
            'license_no' => $params['license_no'] ?? '',
            'mid' => $params['mid'],
            'account' => Member::instance()->where('mid', $params['mid'])->value('account'),
            'store_name' => $params['store_name'],
            'img' => $params['img'],
            'new_store' => 1,
            'pid' => $params['channel_id'],
            'cd' => time(),
            'link_man' =>  $params['link_man'] ?? '',
            'link_mobile' =>  $params['link_mobile'] ?? '',
            'id_card' =>  $params['id_card'] ?? '',
            'remark' =>  $params['remark'] ?? '',
            'enterprise_id' =>  $params['enterprise_id'] ?? 0,
            'flagship' =>  $params['flagship'] ?? 0,
            'is_autovip' =>  $params['is_autovip'] ?? 0,
            'channel_type' =>  $params['channel_type'] ?? 2,
        ];

        if ($params['is_manager'] == 1 || $checkNeeds == 0) {
            $insertMuUser['check_status'] = 1;
        } else {
            $insertMuUser['check_status'] = 0;
        }

        if (isset($params['type']) && in_array($params['type'], [2, 3])) {
            $insertMuUser['type'] = $params['type'];
            $insertMuUser['store_address'] = $params['store_address'];
            $insertMuUser['lat'] = $params['lat'];
            $insertMuUser['lng'] = $params['lng'];
            $insertMuUser['member_share'] = $params['member_share'] ?? '';
            $insertMuUser['stock_share']  = $params['stock_share'];
            $insertMuUser['is_self']  = $params['is_self'] ?? '';
            $insertMuUser['show_points']  = $params['show_points'] ?? 2;
            $insertMuUser['printgoodsdetail']  = $params['printgoodsdetail'] ?? 0;
            $insertMuUser['pay_way'] = implode(',', $params['pay_way']);
            $insertMuUser['guid_commission'] = $params['guid_commission'] ?? 0;
            $insertMuUser['storage_commission'] = $params['storage_commission'] ?? 0;
            $insertMuUser['supplier_id'] = $params['supplier_id'] ?? 0;
            $insertMuUser['cashier_logo'] = $params['cashier_logo'] ?? '';
            $insertMuUser['cashier_customer_code'] = $params['cashier_customer_code'] ?? '';
            $insertMuUser['province'] = $params['province'] ?? 0;
            $insertMuUser['city'] = $params['city'] ?? 0;
            $insertMuUser['area'] = $params['area'] ?? 0;
            $insertMuUser['address'] = $params['address'] ?? '';
            $insertMuUser['online_source'] = $params['online_source'] ?? '0,2';
            $insertMuUser['goods_source'] = $params['goods_source'] ?? 5;
            $insertMuUser['is_autovip'] = $params['is_autovip'] ?? 0;
        }

        $adv = Layout::instance()->info(['cid' => $params['cid'], 'df' => 0, 'type' => 1, 'is_default' => 1]);
        $insertMuUser['adv_temp'] = $adv['id'] ?? 0;
        $insertMuUser['is_pay'] = $params['is_pay'];
        if (isset($params['level'])) {
            $insertMuUser['level'] = $params['level'];
        }
        $newId = Mnuser::instance()->add($insertMuUser);
        if ($insertMuUser['adv_temp']) {
            LayoutService::instance()->storeSetPage([$newId], $adv['id']);
        }
        //todo 生成二维码
        
        if (!$newId) {
            return Normal::returnCode(Normal::FAIL, '开通失败');
        }

        if ($insertMuUser['check_status'] == 0 && $params['is_pay'] == 1) {
            SmsCode::instance()->sendMsg(['cid' => $params['channel_id'], 'temp' => 'storecheck', 'code' => $params['store_name']]);
        }
        return Normal::returnCode(Normal::SUC, '开通成功', [
            'mn_store' => $newId
        ]);
    }
}